//
//  HMNetworkTools.swift
//  3.Swift网络请求方法的封装
//
//  Created by itcastteacher on 17/1/6.
//  Copyright © 2017年 itcastteacher. All rights reserved.
//

import UIKit


enum HTTPMethod: Int {
    case GET
    case POST
}

import AFNetworking

class HMNetworkTools: AFHTTPSessionManager {
    
    //声明单例对象
    static let shared: HMNetworkTools = {
        let tools = HMNetworkTools(baseURL: nil)
        //设置支持解析text/html
        tools.responseSerializer.acceptableContentTypes?.insert("text/plain")
        return tools
    }()
    
    //封装get和post请求的核心方法
    func request(method: HTTPMethod, urlString: String, parameters: Any?,finished: @escaping (Any?,Error?) -> ()) {
        
        let successClosure = { (task:URLSessionDataTask, resp:Any?) -> () in
           //执行闭包
            finished(resp, nil)
        }
        
        let failureClosure = { (task: URLSessionDataTask?, error: Error) -> () in
            print(error)
            finished(nil, error)
        }
        
        
        if method == .GET {
            //调用get
            self.get(urlString, parameters: parameters, progress: nil, success: successClosure, failure: failureClosure)
        }else {
            //调用POSt
            self.post(urlString, parameters: parameters, progress: nil, success: successClosure, failure: failureClosure)
        }
    }

}
















